package org.shop.controller.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Complains;
import org.shop.entity.Merchant;
import org.shop.entity.Orders;
import org.shop.entity.Users;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.ComplainsService;
import org.shop.service.MerchantService;
import org.shop.service.OrdersService;
import org.shop.service.UserService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class ComplainsController {

	private static Logger logger = LogManager.getLogger(ComplainsController.class);
	
	@Autowired
	private ComplainsService complainsService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private UserService userService;
	
	/**
	 * 投诉建议
	 * @param req
	 * @return
	 */
	@RequestMapping("app/addComplains")
	@ResponseBody
	public Map<String,Object> addComplains(HttpServletRequest req){
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
		//转换成多部分request  
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
		Map<String,Object> map = new HashMap<String,Object>();
		String photoStr = null;
		FTPClient ftpClient =null; 
		InputStream is = null;
		//获取的值
		int urlState = Integer.parseInt(multiRequest.getParameter("urlState"));
		String complainsContent = multiRequest.getParameter("complainsContent");
		Long goalId = Long.parseLong(multiRequest.getParameter("goalId"));
		Long respondTargerId = Long.parseLong(multiRequest.getParameter("respondTargerId"));
		try{
    		//判断 request 是否有文件上传,即多部分请求
    		if(multipartResolver.isMultipart(req)){
    			//取得request中的所有文件名
    			Iterator<String> iter = multiRequest.getFileNames();
    			//创建ftp链接
    			String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
    			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
    			while(iter.hasNext()){
    				String name=iter.next();
					//取得上传文件
    				List<MultipartFile> fileList = multiRequest.getFiles(name);
    				if(fileList!=null){
    					for(MultipartFile file:fileList){
    						if(file != null){
    							//取得当前上传文件的文件名称
    	    					String myFileName = file.getOriginalFilename();
    	    					myFileName=FtpUtil2.generateFileName(myFileName);
    	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
    	    					if(myFileName.trim() !=""){
    	    						myFileName=FtpUtil2.generateFileName(myFileName);
    	    						//按照比例进行缩小和放大
                                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                    Thumbnails.of(file.getInputStream()).scale(0.2f).toOutputStream(bos);
                                    is = new ByteArrayInputStream(bos.toByteArray());
                                    
    	    						FtpUtil2.upload(myFileName, is, ftpClient);
    	    						if("".equals(photoStr)&&photoStr==null){
    	    							photoStr =ftp_photoDirectory+"/"+myFileName;
    	    						}else{
    	    							photoStr =ftp_photoDirectory+"/"+myFileName;;
    	    						}
    	    					}
    						}
    					}
    				}
				}
    			Complains complains = new Complains();
    			complains.setComplainAnnex(photoStr);
    			complains.setGoalType((byte) urlState);
    			complains.setUserId(ud.getUserId());
    			complains.setGoalId(goalId);
    			complains.setComPlainContent(complainsContent);
    			complains.setRespondTargerId(respondTargerId);
    			int num = complainsService.insertSelective(complains);
    			map.put("num", num);
    			map.put("urlState", urlState);
    			map.put("goalId", goalId);
    		}
		}catch(Exception e){
			e.printStackTrace();
			logger.info(e.getMessage());
			map.put("num", 0);
		}finally {
			try {
				if(ftpClient != null) {
					FtpUtil2.closeConnection(ftpClient);
				}
			}catch(Exception e){
				ftpClient = null;
			}
		}
		return map;
	}
	
	/**
	 * 跳转投诉建议
	 * @param req
	 * @return
	 */
	@RequestMapping("app/toAdvice")
	public String toAdvice(HttpServletRequest req) {
		Integer urlState = Integer.parseInt(req.getParameter("urlState"));
		Long goalId = Long.parseLong(req.getParameter("goalId"));
		Map<String,Object> pramMap = new HashMap<String,Object>();
		try {
			//对商家投诉
			if(urlState==0) {
				Merchant selectByPrimaryKey = merchantService.selectByPrimaryKey(goalId);
				req.setAttribute("name", "对这个商家的投诉,商家名称："+selectByPrimaryKey.getMerchantName());
				pramMap.put("merchantId", selectByPrimaryKey.getMerchantId());
				Users userInfoByConditions = userService.getUserInfoByConditions(pramMap);
				req.setAttribute("respondTargerId", userInfoByConditions.getUserId());
			//对订单投诉
			}else if(urlState==1) {
				Orders selectByPrimaryKey = ordersService.selectByPrimaryKey(goalId);
				req.setAttribute("name", "对这个订单的投诉,订单号为："+selectByPrimaryKey.getOrderNo());
				pramMap.put("merchantId", selectByPrimaryKey.getMerchantId());
				Users userInfoByConditions = userService.getUserInfoByConditions(pramMap);
				req.setAttribute("respondTargerId", userInfoByConditions.getUserId());
			}
			req.setAttribute("goalId", goalId);
			req.setAttribute("urlState", urlState);
		}catch(Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
		}
		return "app/advice";
	}
	
	
}
